#
# openlookup/client/keychain.py
#
# Copyright 2009 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
File storage for RSA private keys

This is intended for use by client applications of OpenLookup.
"""

import os
import sys
from binascii import hexlify, unhexlify

from openlookup.engine.identity import generate, decode_identity

class Error(Exception): pass
class NotFound(Error): pass
class Ambiguous(Error): pass

class KeyChain(object):
    def __init__(self, path='~/.openlookup/private_keys'):
        self.path = os.path.normpath(os.path.expanduser(path))

    def find(self, prefix=''):
        """
        Return an Identity instance whose fingerprint matches the prefix.

        If no suitable key is found, NotFound is raised.  If more than
        one is found, Ambiguous is raised.

        If the prefix is empty and no keys at all are available, a new
        key is created and returned.
        """
        data = self.load()
        keys = [k for k in data if k.startswith(prefix)]

        if len(keys) == 0:
            if prefix:
                raise NotFound
            else:
                self.inform('Adding new private key to "%s".\n' % self.path)
                return self.add()
        elif len(keys) == 1:
            return data[keys[0]]
        else:
            raise Ambiguous

    def add(self):
        try:
            open(self.path, 'r').close()
        except IOError:
            dir = os.path.dirname(self.path)
            if dir and not os.path.exists(dir):
                os.makedirs(dir, 0700)

            open(self.path, 'w').close()
            os.chmod(self.path, 0600)

        identity = generate()
        k = identity.hexdigest()
        v = hexlify(identity.encode_private())

        f = open(self.path, 'a')
        f.write('%s %s\n' % (k, v))
        f.close()

        return identity

    def list(self, prefix=''):
        """
        Print the fingerprints that match the prefix.
        """
        data = self.load()
        keys = [k for k in data if k.startswith(prefix)]
        for key in sorted(keys):
            print key

    def load(self):
        try:
            f = open(self.path, 'r')
        except IOError:
            return {}

        data = {}
        while True:
            s = f.readline()
            if not s:
                return data

            k, v = s.split()
            data[k] = decode_identity(unhexlify(v))

    def inform(self, msg):
        sys.stderr.write(msg)
